package com.kingint.web.portal.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingint.mbg.bas.entity.BasFloor;
import com.kingint.mbg.bas.entity.BasRoom;
import com.kingint.mbg.bas.mapper.BasFloorMapper;
import com.kingint.mbg.bas.mapper.BasRoomMapper;
import com.kingint.mbg.ser.entity.*;
import com.kingint.mbg.ser.mapper.*;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.mbg.sys.mapper.UmsMemberMapper;
import com.kingint.web.admin.base.service.BasOrderTypeHotelTimeService;
import com.kingint.web.admin.serve.service.ActRuVariableService;
import com.kingint.web.portal.base.service.WorkOrderTypeService;
import com.kingint.web.portal.data.service.DataHouseServicesService;
import com.kingint.web.portal.data.service.DataWorkOrderService;
import com.kingint.web.portal.serve.service.ActivitiCancelService;
import com.kingint.web.portal.serve.service.RoomCleanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingint.web.sys.service.UmsAdminService;
import com.kingint.web.util.CharUtil;
import com.kingint.web.util.WorkType;
import com.kingint.web.util.WorkTypeUtil;
import com.kingint.web.vo.CountParam;
import com.kingint.web.vo.RoomCleanBean;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 客房清洁单 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2020-12-30
 */
@Service
public class RoomCleanServiceImpl extends ServiceImpl<SerRoomCleanMapper, SerRoomClean> implements RoomCleanService {

    @Autowired
    private ProcessRuntime processRuntime;
    @Autowired
    private TaskRuntime taskRuntime;
    @Autowired
    private ActivitiCancelService activitiCancelService;
    @Resource
    private UmsAdminService adminService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private SerWorkOrderMapper workOrderMapper;
    @Resource
    private SerRoomCleanMapper serRoomCleanMapper;
    @Resource
    private TaskService taskService;
    @Resource
    private ActRuVariableService actRuVariableService;

    private String repairInstanceKey = RoomCleanBean.PROCESSINSTANCEKEY;
    @Resource
    private BasRoomMapper roomMapper;
    @Resource
    private BasFloorMapper floorMapper;
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private SerReceiveWorkMiddleMapper receiveWorkMiddleMapper;
    @Resource
    private SerCheckWorkMiddleMapper checkWorkMiddleMapper;
    @Resource
    private WorkOrderTypeService workOrderTypeService;

    @Resource
    private BasOrderTypeHotelTimeService basOrderTypeHotelTimeService;
    @Resource
    private DataWorkOrderService dataWorkOrderService;
    @Resource
    private DataHouseServicesService dataHouseServices;

    /**
     * 添加客房清洁工单
     *
     * @param serRoomClean
     * @return
     */
    @Override
    public String addcleanorder(SerRoomClean serRoomClean) {
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        //添加总工单信息
        SerWorkOrder serWorkOrder = new SerWorkOrder();
        BeanUtils.copyProperties(serRoomClean, serWorkOrder);
        serWorkOrder.setSubmitUserId(currentMember.getId());//提交人员
        serWorkOrder.setCreateTime(new Date());
        serWorkOrder.setWorkOrderStatus(0);
        serWorkOrder.setHotelId(currentMember.getHotelId());
        serWorkOrder.setOrderSn(CharUtil.generateOrderSn()); //工单号
        serWorkOrder.setRoomId(serRoomClean.getRoomId());
        serWorkOrder.setRoomNum(roomMapper.selectById(serRoomClean.getRoomId()).getRoomNum());
        serWorkOrder.setWorkTypeId(WorkTypeUtil.getWorkTypeIdByName(WorkType.roomCleanName)); //工单类型
        serWorkOrder.setOrderStatus(6);
        //存入总工单
        int insert = workOrderMapper.insert(serWorkOrder);

        //同时添加ser_receive_work_middle中间表
        SerReceiveWorkMiddle middle = new SerReceiveWorkMiddle();
        middle.setReceiveUserId(serRoomClean.getCleanUserId());
        middle.setWorkId(serWorkOrder.getId());
        middle.setCreateTime(new Date());
        receiveWorkMiddleMapper.insert(middle);

        //同时添加总单与验收人员中间表ser_check_work_middle
        Long checkUserId = serRoomClean.getCheckUserId();
        if(!StringUtils.isEmpty(checkUserId)){
            SerCheckWorkMiddle workMiddle = new SerCheckWorkMiddle();
            workMiddle.setCheckUserId(serRoomClean.getCheckUserId());
            workMiddle.setCreateTime(new Date());
            workMiddle.setWorkId(serWorkOrder.getId());
            checkWorkMiddleMapper.insert(workMiddle);
        }

        String businessKey = "";
        if (insert > 0) {
            businessKey = RoomCleanBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + serWorkOrder.getId();

            //创建查房表信息
            serRoomClean.setWorkId(serWorkOrder.getId());
            int insert1 = serRoomCleanMapper.insert(serRoomClean);
            if (insert1 > 0) {
                HashMap<String, Object> checkroomuser = new HashMap<>();
                checkroomuser.put(RoomCleanBean.ACCEPTNAMEEL, serRoomClean.getCleanUserName());
                if (!StringUtils.isEmpty(serRoomClean.getCheckUserId())) {
                    checkroomuser.put(RoomCleanBean.CHECKNAMEEL, serRoomClean.getCheckUserName());
                    checkroomuser.put(RoomCleanBean.CHECKSTATUS, 1);
                } else {
                    checkroomuser.put(RoomCleanBean.CHECKSTATUS, 0);
                }
                checkroomuser.put(RoomCleanBean.REJECTSTATUS, 0);
                String processInstanceId = activitiCancelService.startProcess(RoomCleanBean.PROCESSINSTANCEKEY, businessKey, checkroomuser);
                //查询运行时的信息
//                Task task = taskService.createTaskQuery()
//                        .processDefinitionKey(RoomCleanBean.PROCESSINSTANCEKEY)
//                        .processInstanceBusinessKey(businessKey)
//                        .singleResult();
                serWorkOrder.setProcessInstanceId(processInstanceId);
                int i = workOrderMapper.updateById(serWorkOrder);

                //工单上报计时
                basOrderTypeHotelTimeService.addtim(currentMember.getHotelId(), serWorkOrder.getId(), WorkType.roomCleanName,new Date().getTime());

                //住客统计
                dataHouseServices.addDataHouseInfo(currentMember.getHotelId(), CountParam.CLEANCOUNT, serRoomClean.getRoomId(), serRoomClean.getRoomNum());

                //总工单统计
                dataWorkOrderService.addwork(currentMember.getHotelId(),CountParam.CLEANCOUNT);


//                //结束流程
//                taskService.complete(task.getId());
                return processInstanceId;
            }

        }
        return null;
    }

    /**
     * 完成节点
     *
     * @return
     */
    @Override
    public Boolean acceptorder(Integer id, Integer checkstate) {
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        String businessKey = RoomCleanBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + id;
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(id);
        Task task = taskService.createTaskQuery()
                .processInstanceId(serWorkOrder.getProcessInstanceId())
                .singleResult();
//        serWorkOrder.setOrderStatus(2);
        //查询运行时的信息
        if (StringUtils.isEmpty(checkstate)) {
            serWorkOrder.setOrderStatus(2);
            activitiCancelService.complete(id, RoomCleanBean.PROCESSINSTANCEKEY, businessKey);
        } else if (checkstate == 3){
            serWorkOrder.setOrderStatus(3);
            activitiCancelService.complete(id, RoomCleanBean.PROCESSINSTANCEKEY, businessKey);
            workOrderMapper.updateById(serWorkOrder);
            basOrderTypeHotelTimeService.deltim(currentMember.getHotelId(),id,WorkType.roomCleanName);
            return true;
        } else {//验收相关的信息
            if (checkstate == 0){
                serWorkOrder.setOrderStatus(2);
            }else {
                serWorkOrder.setEndTime(new Date());//完成时间
                serWorkOrder.setOrderStatus(5);
                //判断是否超时
                workOrderTypeService.judgeWorkOrderIsTimeOut(currentMember.getId(),serWorkOrder.getId(), WorkType.roomCleanName);
            }

            //无法直接修改变量的值，因为存在2个相同名字的变量，activiti的机制会存在2个相同的变量，正在使用的将会有taskid，另一个则没有
            //所有目前直接操作数据库实现，后期看能否完善
//            QueryWrapper<ActRuVariable> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("PROC_INST_ID_", serWorkOrder.getProcessInstanceId()).eq("TASK_ID_", task.getId())
//                    .eq("NAME_", RoomCleanBean.REJECTSTATUS).eq("TYPE_", "integer");
//            List<ActRuVariable> list = actRuVariableService.list(queryWrapper);
//
//
//            ActRuVariable actRuVariable = new ActRuVariable();  //new一个新类，获得上面的id用来更新，防止变量更改后，taskid不同引起错误
//            actRuVariable.setId(list.get(0).getId());
//            actRuVariable.setLong1(checkstate.longValue());
//            actRuVariableService.updateById(actRuVariable);
//            activitiCancelService.complete(id, RoomCleanBean.PROCESSINSTANCEKEY, businessKey);

            if(!StringUtils.isEmpty(task)){
                Map<String,Object> map=new HashMap<>();
                map.put(RoomCleanBean.REJECTSTATUS, checkstate);
                taskService.setVariables(task.getId(),map);//选择网关支路
                taskService.complete(task.getId());//完成验收支路
            }
        }
        //更新
        workOrderMapper.updateById(serWorkOrder);
        basOrderTypeHotelTimeService.deltim(currentMember.getHotelId(),serWorkOrder.getId(),WorkType.roomCleanName);
        return true;
    }

    @Override
    public Boolean acceptorder1(Integer id, Integer checkstate) {
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        String businessKey = RoomCleanBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + id;
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(id);
        Task task = taskService.createTaskQuery()
                .processInstanceId(serWorkOrder.getProcessInstanceId())
                .singleResult();
//        serWorkOrder.setOrderStatus(2);
        //查询运行时的信息
            serWorkOrder.setOrderStatus(2);
            serWorkOrder.setStartTime(new Date());//开始处理时间
            activitiCancelService.complete(id, RoomCleanBean.PROCESSINSTANCEKEY, businessKey);
        //更新
        workOrderMapper.updateById(serWorkOrder);
        return true;
    }

    @Override
    public SerRoomClean getRoomCleanInfo(Integer id) {
        SerRoomClean serRoomClean = serRoomCleanMapper.selectById(id);
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(serRoomClean.getWorkId());
        serRoomClean.setRoomId(serWorkOrder.getRoomId());
        serRoomClean.setOrderStaus(serWorkOrder.getOrderStatus());//工单状态
        serRoomClean.setOrderSn(serWorkOrder.getOrderSn());//工单号
        BasRoom basRoom = roomMapper.selectById(serWorkOrder.getRoomId());
        serRoomClean.setRoomNum(basRoom.getRoomNum());//房间信息
        BasFloor basFloor = floorMapper.selectById(basRoom.getFloorId());
        serRoomClean.setFloorId(basFloor.getId());
        serRoomClean.setFloorName(basFloor.getFloorName());//楼层信息
        if (!StringUtils.isEmpty(serRoomClean.getCheckUserId())){
            UmsMember umsMember = memberMapper.selectById(serRoomClean.getCheckUserId());//检查人
            serRoomClean.setCheckUserName(umsMember.getUsername());
        }
        UmsMember umsMember1 = memberMapper.selectById(serRoomClean.getCleanUserId());
        serRoomClean.setCleanUserName(umsMember1.getUsername());
        return serRoomClean;
    }
}
